package io.github.enbool;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.support.WebApplicationContextUtils;

import io.github.enbool.domain.User;
import io.github.enbool.service.UserService;
import io.github.enbool.util.UserUtil;

/**
 * 用户信息相关的filter
 * 
 * @author 晓风轻 https://xwjie.github.io/PLMCodeTemplate/
 *
 */
@Configuration
@Order(1)
@WebFilter(filterName = "httpFilter", urlPatterns = "/*")
public class UserFilter implements Filter {
	private Logger logger = LoggerFactory.getLogger(getClass());

	private UserService userService;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		logger.info("init httpFilter");
		ServletContext servletContext = filterConfig.getServletContext();
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		userService = (UserService) ctx.getBean("userService");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		// 得到用户个人相关的信息（登陆的用户，用户的语言）
		fillUserInfo((HttpServletRequest) request);

		try {
			chain.doFilter(request, response);
		} finally {
			// 由于tomcat线程重用，记得清空
			clearAllUserInfo();
		}
	}

	private void clearAllUserInfo() {
		UserUtil.clearAllUserInfo();
	}

	private void fillUserInfo(HttpServletRequest request) {

		UserUtil.setIP(request);
		// 用户信息
		User user = userService.getCurrentUser(request);
		if (user != null) {
			UserUtil.setUser(user);
			return;
		}
	}

	@Override
	public void destroy() {

	}

}
